﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Media;
using System.Xml;

namespace WPFTools {
    public class VCXmlTools
    {
        private RichTextBox rtbLog;
        public VCXmlTools(RichTextBox _rtbLog) {
            rtbLog = _rtbLog;
        }

        public XmlNode? GetInputLibsNode(XmlDocument xmlDoc, bool isDebug = true) {
            if (xmlDoc == null) { return null; }
            if (!xmlDoc.HasChildNodes) {
                return null;
            }

            foreach (XmlNode node in xmlDoc.ChildNodes) {// 第一层：两个子节点，xml 规格定义和主节点 VisualStudioProject
                if (!node.HasChildNodes) {
                    continue;
                }
                foreach (XmlNode node2 in node.ChildNodes) {// 第二层：六个子节点，包含 Configurations， 找到他
                    if (node2.Name != "Configurations") {
                        continue;
                    }
                    foreach (XmlNode node3 in node2.ChildNodes) {// 第三层：各个配置Configuration节点
                        var attrsOfNode3 = node3.Attributes;
                        if (attrsOfNode3 == null) {
                            continue;
                        }
                        var attr = attrsOfNode3.GetNamedItem("Name");
                        if (attr == null) {
                            continue;
                        }
                        else if (attr.InnerText != (isDebug ? "Debug|Win32" : "Release|Win32")) {
                            continue;
                        }
                        foreach (XmlNode node4 in node3.ChildNodes) {// 第四层：Configuration 下的各种 Tool 节点，包含 VCLinkerTool
                            var attrsOfNode4 = node4.Attributes;
                            if (attrsOfNode4 == null) {
                                continue;
                            }
                            var attrNameNodeOfNode4 = attrsOfNode4.GetNamedItem("Name");
                            if (attrNameNodeOfNode4 == null) {
                                continue;
                            }
                            var attrNameOfNode4 = (XmlAttribute)attrNameNodeOfNode4;
                            if (attrNameOfNode4.InnerText != "VCLinkerTool") {
                                continue;
                            }
                            var attrAdditionalDependenciesNode = attrsOfNode4.GetNamedItem("AdditionalDependencies");
                            // 如果没找到就创建一个然后返回
                            if (attrAdditionalDependenciesNode == null) {
                                var newAttrNode = xmlDoc.CreateAttribute("AdditionalDependencies");
                                attrsOfNode4.InsertAfter(newAttrNode, attrNameOfNode4);
                                attrAdditionalDependenciesNode = newAttrNode;
                            }
                            return attrAdditionalDependenciesNode;
                        }
                    }
                }
            }
            return null;
        }
        [Obsolete]
        public XmlNode? GetInputLibsNode(string xmlDocPath, bool isDebug = true)
        {
            var xmlDoc = new XmlDocument();
            // 不加这一行就不支持 GB2312 编码
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            xmlDoc.Load(xmlDocPath);
            // 
            return GetInputLibsNode(xmlDoc, isDebug);
        }

        public List<string>? GetInputLibs(XmlDocument xmlDoc, bool isDebug = true) {
            var result = new List<string>();

            var inputLibsNode = this.GetInputLibsNode(xmlDoc, isDebug);
            if (inputLibsNode == null) {
                Logger.WriteLog($"没有找到项目 {xmlDoc.Name} 的输入库节点！\n", rtbLog, Colors.Red);
                return null;
            }

            if (string.IsNullOrEmpty(inputLibsNode.InnerText)) {
                return result;
            }

            result.AddRange(inputLibsNode.InnerText.Split(' '));
            result = result.Distinct().Where(item => !string.IsNullOrEmpty(item)).ToList();
            return result;
        }

        public bool AddInputLibs(XmlDocument xmlDoc, List<string> listLibsTobeAdd ,bool isDebug = true) {
            if (listLibsTobeAdd == null || xmlDoc == null) {
                Logger.WriteLog($"AddInputLibs 输入参数有 null！\n", rtbLog, Colors.Red);
                return false;
            }

            var listInputLibs = this.GetInputLibs(xmlDoc, isDebug);
            if(listInputLibs == null) {
                Logger.WriteLog($"没有找到项目 {xmlDoc.Name} 的输入库节点！\n", rtbLog, Colors.Red);
                return false;
            }

            var inputLibsNode = this.GetInputLibsNode(xmlDoc, isDebug);
            if (inputLibsNode == null) {
                Logger.WriteLog($"没有找到项目 {xmlDoc.Name} 的输入库节点！\n", rtbLog, Colors.Red);
                return false;
            }

            foreach (var item in listLibsTobeAdd) {
                listInputLibs.AddRange(listLibsTobeAdd);
                listInputLibs = listInputLibs.Distinct().Where(item => !string.IsNullOrEmpty(item)).ToList();
                inputLibsNode.InnerText = string.Join(" ", listInputLibs);
            }
            
            return true;
        }
        public bool AddInputLib(XmlDocument xmlDoc, string libTobeAdd, bool isDebug = true) {
            var listLibsTobeAdd = new List<string>();
            listLibsTobeAdd.Add(libTobeAdd);
            return this.AddInputLibs(xmlDoc, listLibsTobeAdd, isDebug);
        }

        public bool SaveInGB2312(XmlDocument xmlDoc, string xmlDocPath) {
            // 保存
            System.Text.Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            var enc = System.Text.Encoding.GetEncoding("gb2312");
            using (TextWriter sw = new StreamWriter(xmlDocPath, false, enc)) { //Set encoding
                xmlDoc.Save(sw);
            }
            return true;
        }
    }
}
